package com.gs.spring.core.initializing;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionVisitor;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.StringValueResolver;

public class SimpleBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

	private Set<String> obscenities;
	public SimpleBeanFactoryPostProcessor() {
		obscenities = new HashSet<String>();
	}
	
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
			throws BeansException {
		System.out.println("init SimpleBeanFactoryPostProcessor");
		String[] beanNames = beanFactory.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            BeanDefinition bd = beanFactory.getBeanDefinition(beanName);
            StringValueResolver valueResolver = new StringValueResolver() {
                public String resolveStringValue(String strVal) {
                    if (isObscene(strVal)) return "****";
                    return strVal;
            } };
            BeanDefinitionVisitor visitor =
                new BeanDefinitionVisitor(valueResolver);
            visitor.visitBeanDefinition(bd);
        }		
	}
	private boolean isObscene(Object value) {
        String potentialObscenity = value.toString().toUpperCase();
        return this.obscenities.contains(potentialObscenity);
}
    public void setObscenities(Set<String> obscenities) {
        this.obscenities.clear();
        for (String obscenity : obscenities) {
            this.obscenities.add(obscenity.toUpperCase());
        }
}
}
